package cn.tedu.zhyl.dictoption.service.impl;

import cn.tedu.zhyl.base.exception.ServiceException;
import cn.tedu.zhyl.base.response.StatusCode;
import cn.tedu.zhyl.dict.mapper.DictMapper;
import cn.tedu.zhyl.dict.pojo.dto.DictQuery;
import cn.tedu.zhyl.dict.pojo.vo.DictVO;
import cn.tedu.zhyl.dictoption.mapper.DictOptionMapper;
import cn.tedu.zhyl.dictoption.pojo.dto.DictOptionQuery;
import cn.tedu.zhyl.dictoption.pojo.dto.DictOptionSaveParam;
import cn.tedu.zhyl.dictoption.pojo.entity.DictOption;
import cn.tedu.zhyl.dictoption.pojo.vo.DictOptionVO;
import cn.tedu.zhyl.dictoption.service.DictOptionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class DictOptionServiceImpl implements DictOptionService {

    @Autowired
    DictMapper dictMapper;

    @Autowired
    DictOptionMapper dictOptionMapper;


    @Override
    public List<DictOptionVO> selectDictOption(DictOptionQuery dictOptionQuery) {
        List<DictOptionVO> list =dictOptionMapper.selectDictOption(dictOptionQuery);
        return list;
    }

    @Override
    public void saveDictOptionSaveParanm(DictOptionSaveParam dictOptionSaveParam) {
        DictOption dictOption =new DictOption();
        BeanUtils.copyProperties(dictOptionSaveParam,dictOption);
        if (dictOption.getId() == null) {
            dictOption.setCreateTime(new Date());
            dictOptionMapper.insert(dictOption);
        } else {
            dictOption.setUpdateTime(new Date());
            dictOptionMapper.update(dictOption);
        }
    }

    @Override
    public void delectDictoption(Long id) {
        dictOptionMapper.delete(id);
    }

    @Override
    public List<DictOptionVO> selectDictOptionByCode(String code) {
        log.debug("code={}",code);
        DictQuery dictQuery = new DictQuery();
        dictQuery.setCode(code);
        List<DictVO> dictVOList = dictMapper.selectDict(dictQuery);
        if(dictVOList!=null && dictVOList.size()>0){
            DictVO dictVO =dictVOList.get(0);
            DictOptionQuery dictOptionQuery =new DictOptionQuery();//封装字典项查询对象
            dictOptionQuery.setDictId(dictVO.getId());//给字典项查询对象设置字典Id
            List<DictOptionVO> dictOptionVOList = dictOptionMapper.selectDictOption(dictOptionQuery);//查询字典项
            return dictOptionVOList;//返回查到的该字典code对应的所有字典项
        }
        //如果根据code查不到字典数据，抛出字典数据不存在的异常
        throw new ServiceException(StatusCode.FAIL_OPERATION);
    }


}
